/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.pacs.websocket;

import com.baseWebSocket.BaseServer;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class StartServer extends BaseServer {

    private Message message = new Message();

    private Gson gson = new Gson();
    private MsgService ms = new MsgService(this);
    private String loginId, clientIp;
    private List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
    private Map<String, ChannelHandlerContext> nameMap = new HashMap<String, ChannelHandlerContext>();
    private Map<ChannelHandlerContext, String> ctxMap = new HashMap<ChannelHandlerContext, String>();
    private BlockingQueue sendMessageQueue = new LinkedBlockingQueue<Message>();//发送消息的队列

    private static StartServer ss;

    public StartServer(int port,int count) throws Exception {
        super(port,count);
        init();
    }

    public void init() {
        ms.start();
    }

    public void stopSendThread() throws InterruptedException {
        Message msg = new Message();
        ms.setFlag(false);
        msg.setType("closeServer");
        getSendQueue().put(msg);

    }

    @Override
    public void onOpen(ChannelHandlerContext chc, HttpRequest hr) {
        System.out.println("open");
        saveUser(chc, hr);

    }

    @Override
    public void onMessage(ChannelHandlerContext chc, String msg) {
        try {
            System.out.println(msg);
            message = gson.fromJson(msg, new TypeToken<Message>() {
            }.getType());
            //  System.out.println(gson.toJson(message));
            getSendQueue().put(message);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void onClose(ChannelHandlerContext chc) {
        if (ctxMap.get(chc) != null) {
            userOut(chc, ctxMap.get(chc));
        }

    }

    private void saveUser(ChannelHandlerContext chc, HttpRequest hr) {
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("con", chc);
//        userList.add(map);
        String name = hr.getUri().replace("/websocket/", "");
        if (name != null && !name.equalsIgnoreCase("")) {
            checkUser(name, chc);
        }

    }

    public void checkUser(String name, ChannelHandlerContext chc) {
        if (nameMap.get(name) != null) {
            userOut(nameMap.get(name), name);

        } else {
            System.out.println(name + " 已登陆");
            ctxMap.put(chc, name);
            nameMap.put(name, chc);
        }
    }

    public void userOut(ChannelHandlerContext ctx, String name) {
        Message msg = new Message();
        msg.setType("out");
        msg.setBody("您的账号在其他地方登陆");
        send(ctx.channel(), gson.toJson(msg));
        ctx.channel().closeFuture();
        ctxMap.remove(nameMap.get(name));
        nameMap.remove(name);
        System.out.println(name + " 已退出");
    }

    public Map<ChannelHandlerContext, String> getCtxMap() {
        return ctxMap;
    }

    public Map<String, ChannelHandlerContext> getNameMap() {
        return nameMap;
    }

   

    private void sayToAllOffline(String loginId) {

//        getAllUser();
//        Message msg = new Message();
//        msg.setType("offline");
//        msg.setBody(loginId);
//        //msg.setBody(gson.toJson(userList));
//        for (String key : allUserId.keySet()) {
//
//            send(allUserId.get(key).getCon(), gson.toJson(msg));
//        }
    }

//    private List getAllUser() {
//        try {
//            WebClient cli = null;
//            userList = new ArrayList<WebClient>();
//            for (String key : allUserId.keySet()) {
//                cli = allUserId.get(key).clone();
//                cli.setCon(null);
//
//                userList.add(cli);
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return userList;
//
//    }
    private void removeUser(String loginId) {
        try {
            // allUserId.get(loginId).getCon().getChannel().close();
        } catch (Exception e) {

        }

    }

    public void sendClose(ChannelHandlerContext chc) {
        try {
            //  send(chc, "{\"type\":\"" + Type.CLOSE + "\"}");
            // chc.getChannel().close();
        } catch (Exception e) {
            // e.printStackTrace();
        }

    }

    public BlockingQueue getSendQueue() {
//        if (sendMessageQueue == null) {
//            new LinkedBlockingQueue<Message>();
//        }
        return sendMessageQueue;
    }

    public static void main(String[] args) {
        try {
            final StartServer sss = new StartServer(13134,1);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        sss.run();

                    } catch (Exception ex) {

                    }
                }
            }).start();

            Thread.sleep(5000);
//                      System.out.println("----------------------");
            sss.closeServer();

        } catch (Exception ex) {

        }

    }

    @Override
    public void httpReq(ChannelHandlerContext chc, HttpRequest hr, HttpResponse hr1) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}
